package http

import (
	"embed"
	"github.com/xiyoufang/cloud-syncer/internal/http/handler"
	"io/fs"
	"net/http"
)

//go:embed website/*
var websiteFiles embed.FS

const websiteRoot = "website"

func StartWebServer(bindAddr string) error {
	if root, err := fs.Sub(websiteFiles, websiteRoot); err != nil {
		return err
	} else {
		fileServer := http.FileServer(http.FS(root))
		http.Handle("/", fileServer)    // 网站前端
		apiRouter := http.NewServeMux() // 创建 API 路由
		apiRouter.HandleFunc("/api/overview", handler.OverviewHandler)
		apiRouter.HandleFunc("/api/history", handler.HistoryHandler)
		apiRouter.HandleFunc("/api/file", handler.FileHandler)
		apiRouter.HandleFunc("/api/statistics", handler.StatisticsHandler)
		apiRouter.HandleFunc("/api/login", handler.LoginHandler)
		apiRouter.HandleFunc("/api/logout", handler.LogoutHandler)
		apiRouter.HandleFunc("/api/log", handler.LogHandler)

		http.Handle("/api/", corsMiddleware(jwtMiddleware(apiRouter))) // 使用 CORS 中间件
		if err = http.ListenAndServe(bindAddr, nil); err != nil {
			return err
		}
		return nil
	}
}
